package com.example.design_patterns.singleton_pattern;

public class Singleton {

    //懒汉式
    private  static Singleton singleton =null;

    //饿汉式
    private static Singleton singleton1 = new Singleton();

    //双重检查锁，在保证线程安全的前提下依然能保持高性能
    private volatile static Singleton singleton2;


    //饿汉式加锁，线程安全
    public synchronized static Singleton getInstance() {
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }

    //双重检查锁
    public static Singleton getInstance2(){
        if(singleton2 == null){
            synchronized (Singleton.class){
                if(singleton2 == null){
                    singleton2 = new Singleton();
                }
            }
        }
        return singleton2;
    }

    /**
     * 构造器私有化：很关键
     */
    private Singleton() {
    }






}

class test1{

    public static void main(String[] args) {
        new Thread(() -> {
            for(int i=0;i<10;i++){
                System.out.println(Singleton.getInstance());
            }
        },"A").start();
        new Thread(() -> {
            for(int i=0;i<10;i++){
                System.out.println(Singleton.getInstance());
            }
        },"B").start();
    }
        }
